package cn.com.captureNetPacket;

import cn.com.captureNetPacket.model.NetworkCardInfo;
import org.jnetpcap.packet.PcapPacket;
import org.jnetpcap.packet.PcapPacketHandler;
import lombok.extern.slf4j.Slf4j;
import java.util.LinkedList;

@Slf4j
public class CorePcapPacketHandler<Object> implements PcapPacketHandler<Object>{

	LinkedList<PcapPacket> pcapPackets = new LinkedList();
	Thread pcapPacketHandlerThread=null;
	public CorePcapPacketHandler(NetworkCardInfo networkCardInfo){
		analysisPacket=new AnalysisPacket(networkCardInfo);
	}

             public AnalysisPacket analysisPacket ;
	@Override
	public void nextPacket(PcapPacket pcapPacket, Object object) {
//		 packet.getCaptureHeader().caplen(),  // 实际捕获的长度
//         packet.getCaptureHeader().wirelen(), // 原来长度
		try {
				pcapPackets.addLast(pcapPacket);
//			pcapPacketHandlerThread.interrupt();
		}catch (Exception e){
			log.error("CorePcapPacketHandler ",e);
		}
	}


	public void initPcapPacketHandler(){
		if (pcapPacketHandlerThread == null) {
			pcapPacketHandlerThread=new Thread(() -> {
				while (analysisPacket.getNetworkCardInfo().isStartCapture()) {
					try {

						while(!pcapPackets.isEmpty()) {
							PcapPacket pcapPacket =pcapPackets.poll();
							if(pcapPacket !=null) {
								analysisPacket.analysisPacket(pcapPacket);
							}
						}
						Thread.sleep(50);
//						Thread.sleep(CaptureNetPacketService.getConfig().getPacketCollectIntervalTime());
					}catch (InterruptedException e){
//						log.debug("pcapPacketHandlerThread InterruptedException sleep 结束，继续进行处理。 {}",e.getMessage());
					}catch (Exception e){
						log.warn("pcapPacketHandlerThread 处理线程出现故障 !!!",e);
					}
				}
			});
			pcapPacketHandlerThread.setName("pcapPacketHandlerThread-cnp-"+analysisPacket.getNetworkCardInfo().getName());
			pcapPacketHandlerThread.setPriority(Thread.MAX_PRIORITY-2);
			pcapPacketHandlerThread.start();
		}
		}
}
